#include "Test.h"
#include "ISysResources.h"


void * CTest::Work(IObject * prtInPara, void * ptrVtOutParaList)
{
	bool bRetVal = false;
	IPacket * ptrPkt = dynamic_cast<IPacket *>(prtInPara);
	shared_ptr<ITrigger> ptrTrigger = nullptr;
	ptrPkt->Open(RESULT_SET_NAME);
	ptrPkt->ReadRecord(1);
	const char * pszConnectKcbpTxt = ptrPkt->GetFieldValueAsString("CnTxt");
	//InitServerSide();
	shared_ptr<IMakeMarket> ptrMakeMarket = nullptr;
	shared_ptr<IStrFun> ptrStrFun = nullptr;
	char szOpenHandleName[CHAR_LEN_64] = { 0 };
	char szCloseHandleName[CHAR_LEN_64] = { 0 };
	::HANDLE hdOpenHandle = 0, hdCloseHandle = 0;
	ptrMakeMarket = Invoke<IMakeMarket>("CMakeMarket", nullptr, nullptr, 0);
	ptrStrFun = Invoke<IStrFun>("CStrFun", nullptr, nullptr, 0);
	if (ptrMakeMarket == nullptr)
	{
		goto __end;
	}
	if (ptrStrFun == nullptr)
	{
		goto __end;
	}
	
	ptrStrFun->ParaVal(szOpenHandleName, sizeof(szOpenHandleName), pszConnectKcbpTxt, "OpenHandle");
	ptrStrFun->ParaVal(szCloseHandleName, sizeof(szCloseHandleName), pszConnectKcbpTxt, "CloseHandle");
	if (!ptrStrFun->IsEmpty(szOpenHandleName))
	{
		ptrTrigger = Invoke< ITrigger >("CGtSemaphore", static_cast<void *>(szOpenHandleName), nullptr, 0);
		//hdOpenHandle = ::OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, false, szOpenHandleName);
	}
	bRetVal = ptrMakeMarket->InitConnect(pszConnectKcbpTxt);
	if (!bRetVal && !ptrStrFun->IsEmpty(szCloseHandleName))
	{
		hdCloseHandle = CreateMutexA(nullptr, false, szCloseHandleName);
	}
	if (ptrTrigger != nullptr)
	{
		ptrTrigger->Trigger(1);
		//::ReleaseSemaphore(hdOpenHandle, 1, nullptr);
		Kernel().WriteLog(string("OpenHandleName=" + string(szOpenHandleName)).c_str());
	}
	else
	{
		char szTmp[CHAR_LEN_32] = { 0 };
		string strErrMsg = string(szOpenHandleName) + '_' + string(itoa(::GetLastError(), szTmp, sizeof(szTmp)));
		Kernel().WriteLog(strErrMsg.c_str());
	}
__end:
	return nullptr;
}
